/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package viewControl;

import entity.*;
import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import util.FileUtils;
import util.GUIUtils;

/**
 *
 * @author Jeppe
 */
public class KontaktPanel extends javax.swing.JPanel {

    public static final int RELATION_FAR = 1;
    public static final int RELATION_MOR = 2;
    public static final int RELATION_ANDET_FAMILIE = 3;
    public static final int RELATION_VAERGE = 4;
    public static final int RELATION_PAEDAGOG = 5;
    public static final int RELATION_PSYKOLOG = 6;
    public static final int RELATION_SAGSBEHANDLER = 7;
    public static final int RELATION_LAEGE = 8;
    private Session session;
    private ArrayList filer;
    private ArrayList filerDerSlettes;
    private ArrayList elever;
    private Laerer currentLaerer;

    /**
     * Creates new form KontaktPanel
     */
    public KontaktPanel(Session session) {
        this.session = session;
        this.currentLaerer = null;
        elever = new ArrayList();
        filer = new ArrayList();
        filerDerSlettes = new ArrayList();
        initComponents();
    }

    public KontaktPanel(Session session, Laerer laerer) {
        this.session = session;
        this.currentLaerer = laerer;
        elever = new ArrayList();
        filer = new ArrayList();
        initComponents();
    }
    
    public void limitPanel(){
        btnSlet.setVisible(false);
    }

    public String getByNavn(String postnr) {
        String result;
        String hql = "from Postnrbynavn where postnr='" + postnr + "'";
        session.beginTransaction();
        Query q = session.createQuery(hql);
        try {
            Postnrbynavn pbn = (Postnrbynavn) q.uniqueResult();
            result = pbn.getBynavn();
        } catch (NullPointerException e) {
            result = "Ugyldigt Postnr.";
        }
        return result;
    }

    private void updateElevCB() {
        cbElev.removeAllItems();
        cbElev.addItem("Elev");
        String hql = "from Elev where udskrevet=null";
        try {
            session.beginTransaction();
            Query q = session.createQuery(hql);
            Object[] eList = q.list().toArray();
            Arrays.sort(eList);
            for (int i = 0; i < eList.length; i++) {
                cbElev.addItem(eList[i]);
            }
            session.getTransaction().commit();
        } catch (HibernateException he) {
            System.out.println(he.getLocalizedMessage());
        }
    }

    protected void update() {
        if (currentLaerer == null) {
            Kontaktperson kontaktIndex = null;
            if (cbKontaktPerson.getSelectedIndex() > 0) {
                kontaktIndex = (Kontaktperson) cbKontaktPerson.getSelectedItem();
            }
            // Updater elev combobox
            updateElevCB();
            cbKontaktPerson.removeAllItems();
            cbKontaktPerson.addItem("Kontaktperson");
            String hql = "from Kontaktperson";
            try {
                session.beginTransaction();
                Query q = session.createQuery(hql);
                Object[] kpList = q.list().toArray();
                Arrays.sort(kpList);
                for (int i = 0; i < kpList.length; i++) {
                    cbKontaktPerson.addItem(kpList[i]);
                }
                session.getTransaction().commit();
            } catch (HibernateException he) {
                System.out.println(he.getLocalizedMessage());
            }

            GUIUtils.clearFields(this);
            if (cbKontaktPerson.getSelectedIndex() > 0) {
                btnGem.setText("Gem ændringer");
            } else {
                btnGem.setText("Opret ny kontaktperson");
            }
            if (kontaktIndex != null) {
                cbKontaktPerson.setSelectedItem(kontaktIndex);
            } else {
                cbKontaktPerson.setSelectedIndex(0);
            }
        } else if (currentLaerer != null) {
            int kontaktIndex = cbKontaktPerson.getSelectedIndex();
            cbKontaktPerson.removeAllItems();
            cbKontaktPerson.addItem("Kontaktperson");
            cbElev.removeAllItems();
            cbElev.addItem("Elev");
            ArrayList holdfags = new ArrayList();
            ArrayList elever = new ArrayList();
            ArrayList kontakter = new ArrayList();
            ArrayList finallistKontaktPerson = new ArrayList();
            ArrayList finallistElev = new ArrayList();
            holdfags.addAll(currentLaerer.getHoldfags());
            for (int i = 0; i < holdfags.size(); i++) {
                Holdfag hf = (Holdfag) holdfags.get(i);
                elever.addAll(hf.getHold().getElevs());
                for (int j = 0; j < elever.size(); j++) {
                    Elev e = (Elev) elever.get(i);
                    kontakter.addAll(e.getKontaktpersons());
                    if (!finallistElev.contains(e)) {
                        finallistElev.add(e);
                        cbElev.addItem(e);
                    }
                    for (int kp = 0; kp < kontakter.size(); kp++) {
                        Kontaktperson k = (Kontaktperson) kontakter.get(kp);
                        if (!finallistKontaktPerson.contains(k)) {
                            finallistKontaktPerson.add(k);
                            cbKontaktPerson.addItem(k);
                        }
                    }
                }
            }

            GUIUtils.clearFields(this);
            if (cbKontaktPerson.getSelectedIndex() > 0) {
                btnGem.setText("Gem ændringer");
            } else {
                btnGem.setText("Opret ny kontaktperson");
            }
            cbKontaktPerson.setSelectedIndex(kontaktIndex);
        }

    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        cbKontaktPerson = new javax.swing.JComboBox();
        btnVedhaeftFil = new javax.swing.JButton();
        btnOpenFil = new javax.swing.JButton();
        btnFjernValgteFil = new javax.swing.JButton();
        jScrollPane6 = new javax.swing.JScrollPane();
        listFiler = new javax.swing.JList();
        jScrollPane4 = new javax.swing.JScrollPane();
        txtaNoter = new javax.swing.JTextArea();
        jScrollPane3 = new javax.swing.JScrollPane();
        listElev = new javax.swing.JList();
        cbElev = new javax.swing.JComboBox();
        btnTilfojElev = new javax.swing.JButton();
        btnFjernElev = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        txtFnavn = new javax.swing.JTextField();
        txtEnavn = new javax.swing.JTextField();
        txtAdresse = new javax.swing.JTextField();
        txtPostnr = new javax.swing.JTextField();
        txtBy = new javax.swing.JTextField();
        txtTlfPrivat = new javax.swing.JTextField();
        txtEmail = new javax.swing.JTextField();
        txtTlfArb = new javax.swing.JTextField();
        txtWebside = new javax.swing.JTextField();
        txtTlfMob = new javax.swing.JTextField();
        txtRekvKommune = new javax.swing.JTextField();
        cbRelation = new javax.swing.JComboBox();
        btnGem = new javax.swing.JButton();
        btnSlet = new javax.swing.JButton();

        setLayout(null);

        cbKontaktPerson.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Kontaktperson", "kontakt1", "kontakt2" }));
        cbKontaktPerson.setToolTipText("");
        cbKontaktPerson.setMinimumSize(new java.awt.Dimension(57, 20));
        cbKontaktPerson.setNextFocusableComponent(cbRelation);
        cbKontaktPerson.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbKontaktPersonActionPerformed(evt);
            }
        });
        add(cbKontaktPerson);
        cbKontaktPerson.setBounds(20, 20, 570, 20);

        btnVedhaeftFil.setText("Vedhæft Fil");
        btnVedhaeftFil.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnVedhaeftFilActionPerformed(evt);
            }
        });
        add(btnVedhaeftFil);
        btnVedhaeftFil.setBounds(790, 530, 90, 23);

        btnOpenFil.setText("Åben Fil");
        btnOpenFil.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnOpenFilActionPerformed(evt);
            }
        });
        add(btnOpenFil);
        btnOpenFil.setBounds(610, 530, 70, 23);

        btnFjernValgteFil.setText("Slet Fil");
        btnFjernValgteFil.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnFjernValgteFilActionPerformed(evt);
            }
        });
        add(btnFjernValgteFil);
        btnFjernValgteFil.setBounds(890, 530, 70, 23);

        listFiler.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Vedhæftede filer", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11))); // NOI18N
        listFiler.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane6.setViewportView(listFiler);

        add(jScrollPane6);
        jScrollPane6.setBounds(610, 400, 350, 110);

        txtaNoter.setColumns(20);
        txtaNoter.setRows(5);
        txtaNoter.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Noter", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11))); // NOI18N
        txtaNoter.setNextFocusableComponent(btnGem);
        jScrollPane4.setViewportView(txtaNoter);

        add(jScrollPane4);
        jScrollPane4.setBounds(610, 171, 350, 220);

        listElev.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Tilknyttede elever", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11))); // NOI18N
        jScrollPane3.setViewportView(listElev);

        add(jScrollPane3);
        jScrollPane3.setBounds(610, 70, 350, 90);

        cbElev.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Elev", "elev1", "elev2" }));
        cbElev.setNextFocusableComponent(btnTilfojElev);
        cbElev.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbElevActionPerformed(evt);
            }
        });
        add(cbElev);
        cbElev.setBounds(610, 20, 170, 20);

        btnTilfojElev.setText("Tilføj");
        btnTilfojElev.setEnabled(false);
        btnTilfojElev.setNextFocusableComponent(btnFjernElev);
        btnTilfojElev.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnTilfojElevActionPerformed(evt);
            }
        });
        add(btnTilfojElev);
        btnTilfojElev.setBounds(790, 20, 80, 23);

        btnFjernElev.setText("Fjern");
        btnFjernElev.setNextFocusableComponent(txtaNoter);
        btnFjernElev.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnFjernElevActionPerformed(evt);
            }
        });
        add(btnFjernElev);
        btnFjernElev.setBounds(880, 20, 80, 23);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Kontaktperson", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 12), java.awt.Color.black)); // NOI18N
        jPanel1.setLayout(null);

        txtFnavn.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Fornavn", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11))); // NOI18N
        txtFnavn.setNextFocusableComponent(txtEnavn);
        jPanel1.add(txtFnavn);
        txtFnavn.setBounds(20, 90, 170, 40);

        txtEnavn.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Efternavn", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11))); // NOI18N
        txtEnavn.setNextFocusableComponent(txtAdresse);
        jPanel1.add(txtEnavn);
        txtEnavn.setBounds(200, 90, 170, 40);

        txtAdresse.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Adresse", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11))); // NOI18N
        txtAdresse.setNextFocusableComponent(txtPostnr);
        jPanel1.add(txtAdresse);
        txtAdresse.setBounds(20, 150, 170, 40);

        txtPostnr.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "PostNr.", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11))); // NOI18N
        txtPostnr.setNextFocusableComponent(txtTlfPrivat);
        txtPostnr.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtPostnrKeyReleased(evt);
            }
        });
        jPanel1.add(txtPostnr);
        txtPostnr.setBounds(20, 210, 170, 40);

        txtBy.setEditable(false);
        txtBy.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "By", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11))); // NOI18N
        jPanel1.add(txtBy);
        txtBy.setBounds(200, 210, 170, 40);

        txtTlfPrivat.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Tlf. Privat", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11))); // NOI18N
        txtTlfPrivat.setNextFocusableComponent(txtTlfArb);
        jPanel1.add(txtTlfPrivat);
        txtTlfPrivat.setBounds(20, 270, 170, 40);

        txtEmail.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "E-Mail", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11))); // NOI18N
        txtEmail.setNextFocusableComponent(txtWebside);
        jPanel1.add(txtEmail);
        txtEmail.setBounds(20, 330, 170, 40);

        txtTlfArb.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Tlf. Arbejde", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11))); // NOI18N
        txtTlfArb.setNextFocusableComponent(txtTlfMob);
        jPanel1.add(txtTlfArb);
        txtTlfArb.setBounds(200, 270, 170, 40);

        txtWebside.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Webside", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11))); // NOI18N
        txtWebside.setNextFocusableComponent(txtRekvKommune);
        jPanel1.add(txtWebside);
        txtWebside.setBounds(200, 330, 170, 40);

        txtTlfMob.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Tlf. Mobil", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11))); // NOI18N
        txtTlfMob.setNextFocusableComponent(txtEmail);
        jPanel1.add(txtTlfMob);
        txtTlfMob.setBounds(380, 270, 170, 40);

        txtRekvKommune.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Rekvirerende Kommune", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11))); // NOI18N
        txtRekvKommune.setNextFocusableComponent(cbElev);
        jPanel1.add(txtRekvKommune);
        txtRekvKommune.setBounds(20, 390, 170, 40);

        cbRelation.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Relation", "Far", "Mor", "Andet Familie", "Værge", "Pædagog", "Psykolog", "Sagsbehandler", "Læge" }));
        cbRelation.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        cbRelation.setNextFocusableComponent(txtFnavn);
        cbRelation.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbRelationActionPerformed(evt);
            }
        });
        jPanel1.add(cbRelation);
        cbRelation.setBounds(20, 40, 170, 30);

        add(jPanel1);
        jPanel1.setBounds(20, 60, 570, 450);

        btnGem.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        btnGem.setText("Opret Ny Kontaktperson");
        btnGem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGemActionPerformed(evt);
            }
        });
        add(btnGem);
        btnGem.setBounds(20, 530, 180, 23);

        btnSlet.setText("Slet Kontaktperson");
        btnSlet.setEnabled(false);
        btnSlet.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSletActionPerformed(evt);
            }
        });
        add(btnSlet);
        btnSlet.setBounds(210, 530, 130, 23);
    }// </editor-fold>//GEN-END:initComponents

    private void cbKontaktPersonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbKontaktPersonActionPerformed
        updateElevCB();
        ArrayList temparray = new ArrayList();
        elever = new ArrayList();
        filer = new ArrayList();
        filerDerSlettes = new ArrayList();
        if (cbKontaktPerson.getSelectedIndex() > 0) {
            btnGem.setText("Gem ændringer");
            btnSlet.setEnabled(true);
            Kontaktperson kp = (Kontaktperson) cbKontaktPerson.getSelectedItem();
            txtFnavn.setText(kp.getFornavn());
            txtEnavn.setText(kp.getEfternavn());
            txtAdresse.setText(kp.getAdresse());
            if (kp.getPostnrbynavn() != null) {
                txtPostnr.setText(kp.getPostnrbynavn().getPostnr());
                txtBy.setText(getByNavn(txtPostnr.getText()));
            } else {
                txtPostnr.setText("");
                txtBy.setText("");
            }
            txtRekvKommune.setText(kp.getRekvkommune());
            txtEmail.setText(kp.getEmail());
            txtWebside.setText(kp.getWebside());
            txtaNoter.setText(kp.getNoter());
            txtTlfArb.setText("");
            txtTlfMob.setText("");
            txtTlfPrivat.setText("");
            temparray.addAll(kp.getKontakttlfs());
            for (int i = 0; i < temparray.size(); i++) {
                Kontakttlf kt = (Kontakttlf) temparray.get(i);
                switch (kt.getType()) {
                    case 1:
                        txtTlfPrivat.setText(kt.getId().getTlfNr());
                        break;
                    case 2:
                        txtTlfArb.setText(kt.getId().getTlfNr());
                        break;
                    case 3:
                        txtTlfMob.setText(kt.getId().getTlfNr());
                        break;
                }
            }
            cbRelation.setSelectedIndex(kp.getRelation());

            temparray = new ArrayList();
            temparray.addAll(kp.getElevs());
            for (int i = 0; i < temparray.size(); i++) {
                elever.add((Elev) temparray.get(i));
                cbElev.removeItem((Elev) temparray.get(i));
            }
            listElev.setListData(elever.toArray());

            temparray = new ArrayList();
            temparray.addAll(kp.getKontaktfilers());
            for (int i = 0; i < temparray.size(); i++) {
                Kontaktfiler kf = (Kontaktfiler) temparray.get(i);
                File newImage = new File(kf.getId().getFilUri());
                filer.add(newImage);
            }
            listFiler.setListData(filer.toArray());

        } else {
            btnGem.setText("Opret ny kontaktperson");
            btnSlet.setEnabled(false);
            update();
        }
    }//GEN-LAST:event_cbKontaktPersonActionPerformed

    private void btnVedhaeftFilActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnVedhaeftFilActionPerformed
        JFileChooser fc = new JFileChooser();
        int returnVal = fc.showDialog(null, "Vedhæft fil");
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File newFile = fc.getSelectedFile();
            filer.add(newFile);
            listFiler.setListData(filer.toArray());
        }
    }//GEN-LAST:event_btnVedhaeftFilActionPerformed

    private void btnOpenFilActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOpenFilActionPerformed
        if (!listFiler.isSelectionEmpty()) {
            File temp = (File) filer.get(listFiler.getSelectedIndex());
            Desktop dtop = Desktop.getDesktop();
            try {
                dtop.open(temp);
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(null, ex.getLocalizedMessage(), "File Error!", 0);
            }
        }
    }//GEN-LAST:event_btnOpenFilActionPerformed

    private void btnFjernValgteFilActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFjernValgteFilActionPerformed
        if (!listFiler.isSelectionEmpty()) {
            File f = (File) filer.get(listFiler.getSelectedIndex());
            filerDerSlettes.add(f);
            filer.remove(listFiler.getSelectedIndex());
            listFiler.setListData(filer.toArray());
        }
    }//GEN-LAST:event_btnFjernValgteFilActionPerformed

    private void btnTilfojElevActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnTilfojElevActionPerformed
        if (cbElev.getSelectedIndex() > 0) {
            elever.add(cbElev.getSelectedItem());
            listElev.setListData(elever.toArray());
            cbElev.removeItemAt(cbElev.getSelectedIndex());
        }
    }//GEN-LAST:event_btnTilfojElevActionPerformed

    private void btnFjernElevActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFjernElevActionPerformed
        if (!listElev.isSelectionEmpty()) {
            cbElev.addItem(elever.get(listElev.getSelectedIndex()));
            elever.remove(listElev.getSelectedIndex());
            listElev.setListData(elever.toArray());
        }
    }//GEN-LAST:event_btnFjernElevActionPerformed

    private void cbElevActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbElevActionPerformed
        if (cbElev.getSelectedIndex() > 0) {
            btnTilfojElev.setEnabled(true);
        } else {
            btnTilfojElev.setEnabled(false);
        }
    }//GEN-LAST:event_cbElevActionPerformed

    private void btnGemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGemActionPerformed
        if (txtEnavn.getText().length() > 0 && txtFnavn.getText().length() > 0 && cbRelation.getSelectedIndex() > 0) {
            Kontaktperson kp = null;
            if (cbKontaktPerson.getSelectedIndex() > 0) {
                session.beginTransaction();
                kp = (Kontaktperson) cbKontaktPerson.getSelectedItem();
                kp.getKontakttlfs().removeAll(kp.getKontakttlfs());
                kp.getKontaktfilers().removeAll(kp.getKontaktfilers());
                kp.getElevs().removeAll(kp.getElevs());
                session.update(kp);
                session.getTransaction().commit();
                session.flush();
            } else {
                session.beginTransaction();
                kp = new Kontaktperson();
                session.save(kp);
                session.getTransaction().commit();
                session.flush();
            }
            session.beginTransaction();
            kp.setFornavn(txtFnavn.getText());
            kp.setEfternavn(txtEnavn.getText());
            kp.setAdresse(txtAdresse.getText());
            kp.setEmail(txtEmail.getText());
            kp.setWebside(txtWebside.getText());
            kp.setNoter(txtaNoter.getText());
            kp.setRelation(cbRelation.getSelectedIndex());
            kp.setRekvkommune(txtRekvKommune.getText());

            String hql = "from Postnrbynavn where postnr='" + txtPostnr.getText() + "'";
            Query q = session.createQuery(hql);
            Postnrbynavn pbn = (Postnrbynavn) q.uniqueResult();
            kp.setPostnrbynavn(pbn);

            if (txtTlfPrivat.getText().length() == 8) {
                KontakttlfId tlfid = new KontakttlfId(kp.getId(), txtTlfPrivat.getText());
                Kontakttlf nummer = new Kontakttlf(tlfid, kp, 1);
                kp.getKontakttlfs().add(nummer);
            }

            if (txtTlfArb.getText().length() == 8) {
                KontakttlfId tlfid = new KontakttlfId(kp.getId(), txtTlfArb.getText());
                Kontakttlf nummer = new Kontakttlf(tlfid, kp, 2);
                kp.getKontakttlfs().add(nummer);
            }

            if (txtTlfMob.getText().length() == 8) {
                KontakttlfId tlfid = new KontakttlfId(kp.getId(), txtTlfMob.getText());
                Kontakttlf nummer = new Kontakttlf(tlfid, kp, 3);
                kp.getKontakttlfs().add(nummer);
            }

            for (int i = 0; i < kp.getKontakttlfs().size(); i++) {
                Object[] o = (Object[]) kp.getKontakttlfs().toArray();
            }

            for (int i = 0; i < elever.size(); i++) {
                Elev elev = (Elev) elever.get(i);
                elev.getKontaktpersons().add(kp);
                kp.getElevs().add(elev);
            }

            String pre = "AttachedFiles/";
            pre += kp.getFornavn() + kp.getEfternavn();
            File f = new File(pre);
            f.mkdirs();
            for (int i = 0; i < filer.size(); i++) {
                String path = ((File) filer.get(i)).getPath();
                String fName = pre + "/" + ((File) filer.get(i)).getName();
                if (!path.equals(fName)) {
                    try {
                        FileUtils.copy(path, fName);
                    } catch (IOException ex) {
                        JOptionPane.showMessageDialog(null, ex.getLocalizedMessage(), "File Error!", 0);
                    }
                    KontaktfilerId kfid = new KontaktfilerId(kp.getId(), fName);
                    Kontaktfiler kf = new Kontaktfiler(kfid, kp);
                    kp.getKontaktfilers().add(kf);
                }
            }
            session.update(kp);
            session.getTransaction().commit();
            session.flush();

            if (filerDerSlettes.size() > 0) {
                for (int i = 0; i < filerDerSlettes.size(); i++) {
                    File fil = (File) filerDerSlettes.get(i);
                    fil.delete();
                }
            }
            update();
            JOptionPane.showMessageDialog(null, "Kontaktperson er gemt.", "Info", 1);
        } else {
            JOptionPane.showMessageDialog(null, "Kontaktpersonen skal have et fornavn, efternavn og en relation", "Info", 1);
        }
    }//GEN-LAST:event_btnGemActionPerformed

    private void btnSletActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSletActionPerformed
        int result = JOptionPane.showConfirmDialog(null, "Er du sikker på du vil slette den valgte Kontaktperson", "Advarsel", 2);
        if (result == JOptionPane.OK_OPTION) {
            Kontaktperson kp = (Kontaktperson) cbKontaktPerson.getSelectedItem();
            ArrayList temp = new ArrayList();
            temp.addAll(kp.getElevs());
            for (int i = 0; i < temp.size(); i++) {
                Elev e = (Elev) temp.get(i);
                e.getKontaktpersons().remove(kp);
            }           
            if (kp.getKontaktfilers().size() > 0) {
                filerDerSlettes = new ArrayList();
                filerDerSlettes.addAll(kp.getKontaktfilers());
                for (int i = 0; i < filerDerSlettes.size(); i++) {
                    Kontaktfiler kf = (Kontaktfiler) filerDerSlettes.get(i);
                    File newImage = new File(kf.getId().getFilUri());
                    newImage.delete();
                }
            }
            session.beginTransaction();
            session.delete(kp);
            session.getTransaction().commit();
            update();
        }
    }//GEN-LAST:event_btnSletActionPerformed

    private void txtPostnrKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtPostnrKeyReleased
        if (txtPostnr.getText().length() == 4) {
            txtBy.setText(getByNavn(txtPostnr.getText()));
        } else {
            txtBy.setText("");
        }
    }//GEN-LAST:event_txtPostnrKeyReleased

    private void cbRelationActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbRelationActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_cbRelationActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnFjernElev;
    private javax.swing.JButton btnFjernValgteFil;
    private javax.swing.JButton btnGem;
    private javax.swing.JButton btnOpenFil;
    private javax.swing.JButton btnSlet;
    private javax.swing.JButton btnTilfojElev;
    private javax.swing.JButton btnVedhaeftFil;
    private javax.swing.JComboBox cbElev;
    private javax.swing.JComboBox cbKontaktPerson;
    private javax.swing.JComboBox cbRelation;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JScrollPane jScrollPane6;
    private javax.swing.JList listElev;
    private javax.swing.JList listFiler;
    private javax.swing.JTextField txtAdresse;
    private javax.swing.JTextField txtBy;
    private javax.swing.JTextField txtEmail;
    private javax.swing.JTextField txtEnavn;
    private javax.swing.JTextField txtFnavn;
    private javax.swing.JTextField txtPostnr;
    private javax.swing.JTextField txtRekvKommune;
    private javax.swing.JTextField txtTlfArb;
    private javax.swing.JTextField txtTlfMob;
    private javax.swing.JTextField txtTlfPrivat;
    private javax.swing.JTextField txtWebside;
    private javax.swing.JTextArea txtaNoter;
    // End of variables declaration//GEN-END:variables
}
